HRESULT SaveWaveFile(HANDLE hFile, BYTE* buffer, int dwChunkSize,  WAVEFORMATEXTENSIBLE* wfx)
{
	int lpNumberOfBytesWritten;
	//RIFF
	if (0 == WriteFile(hFile, "RIFF", sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() ); 
	
	//Size of File without RIFF
	DWORD SizeFile = 20 + dwChunkSize + sizeof(WAVEFORMATEXTENSIBLE);
	if (0 == WriteFile(hFile, &SizeFile, sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() );

	if (0 == WriteFile(hFile, "WAVE", sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() );

	if (0 == WriteFile(hFile, "fmt ", sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() );
	
	DWORD SizeWfx = sizeof(WAVEFORMATEXTENSIBLE);
	if (0 == WriteFile(hFile, &SizeWfx, sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() ); 

	if (0 == WriteFile(hFile, wfx, sizeof(WAVEFORMATEXTENSIBLE), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() ); 

	if (0 == WriteFile(hFile, "data", sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() );

	if (0 == WriteFile(hFile, &dwChunkSize, sizeof(DWORD), (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() );
	
	if (0 == WriteFile(hFile, buffer, dwChunkSize, (LPDWORD)&lpNumberOfBytesWritten, NULL) )
		return HRESULT_FROM_WIN32( GetLastError() ); 

	return S_OK;
}